import React, {useState, useRef, useEffect} from 'react'
import {message, Button, Divider, Popconfirm} from 'antd'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table'
import {connect} from 'umi'
import {PlusOutlined} from '@ant-design/icons'
import {
  getCredentialList,
  saveOrUpdateCredential,
  deleteCredentialById,
  saveOrDeleteHang,
  getCredentialItemList,
  credentialBpm
} from '../service'
import moment from 'moment';
import AddForm from './components/AddForm';
import Details from './components/Details';
import store from 'store2';

const TableList = ({global={},currentUser}) => {
  const actionRef = useRef();
  const {options = {}} = global;
  const {orgTree = []} = options || {};
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [record, setRecord] = useState(null);
  const [config, setConfig] = useState({});
  const [detailsVisible,setDetailsVisible] = useState(false);
  const [title,setTitle] = useState(null);

  useEffect(() => {
    getCredentialItemList().then(res => {
      if (res.flag) {
        setConfig(res.data);
      } else {
        message.error("获取资质配置子项错误！")
      }
    });
  }, []);

  const addCredential = (record) => {
    if(record){
      setRecord(record);
    }
    setVisible(true)
  };

  const dismissOrDetails = (record,title) => {
    setDetailsVisible(true);
    setRecord(record);
    setTitle(title);
  };

  const handleCancel = () => {
    setVisible(false);
    setDetailsVisible(false);
    setRecord(null);
  };

  const handleSubmit = (values) => {
    setLoading(true)
    return saveOrUpdateCredential(values).then((res) => {
      setVisible(false);
      if (res.flag) {
        setDetailsVisible(false);
        message.success('操作成功！');
        store.remove(`personnel-credential-` + currentUser.id);
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  const saveOrDelHang = (credentialId, type) => {
    setLoading(true);
    saveOrDeleteHang(credentialId, type).then(res => {
      if (res.flag) {
        message.success('操作成功！');
        handleCancel();
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  const delCredential = (id) => {
    setLoading(true);
    deleteCredentialById(id).then(res => {
      if (res.flag) {
        message.success('删除成功！');
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  const sendBpm = (id) => {
    credentialBpm(id).then(res => {
      if (res.flag){
        message.success(`发起成功!`);
        window.open(res.data);
      }else {
        message.error(res.error);
      }
    });
  };

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '证书编号',
      hideInSearch: true,
      dataIndex: 'credentialNo',
    },
    {
      title: '职称系列',
      hideInSearch: true,
      dataIndex: 'jobSeries',
    },
    {
      title: '证书级别',
      hideInSearch: true,
      dataIndex: 'credentialLevel',
    },
    {
      title: '资格名称',
      hideInSearch: true,
      dataIndex: 'credentialName',
    },
    {
      title: '挂靠公司',
      hideInSearch: true,
      dataIndex: 'companyId',
      render: (text) => {
        return text ? orgTree.find(item => (item.value === text)).title : '';
      },
    },
    {
      title: '授予时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      render: (text) => {
        return moment(text).format('YYYY-MM-DD');
      },
    },
    {
      title: '是否挂靠',
      hideInSearch: true,
      dataIndex: 'hangStatus',
      valueEnum: {
        0: {text: '未审核', status: 'Default'},
        1: {text: '审核中', status: 'Processing'},
        2: {text: '已挂靠', status: 'Success'},
        4: {text: '解除中', status: 'Processing'},
        5: {text: '已解除', status: 'Error'},
      },
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      valueEnum: {
        0: {text: '未审核', status: 'Default'},
        1: {text: '已审核', status: 'Success'},
        2: {text: '被驳回', status: 'Default'},
      },
    },
    {
      title: '驳回原因',
      dataIndex: 'reason',
      hideInSearch: true,
      ellipsis: true,
      width: 150,
      render: (text) => {
        return text !== '-' ? text : '';
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          {(record.status === 0 || record.status === 2) && <> <a onClick={() => addCredential(record)}>编辑</a><Divider type="vertical"/></>}
          {(record.status === 1 && (record.hangStatus === 0 || record.hangStatus === 5)) && <>
            <a onClick={() => dismissOrDetails(record,'详情')}>详情</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否申请挂靠？" cancelText='取消' okText='确认' onConfirm={() => sendBpm(record.id)}>
              <a>发起审批</a>
            </Popconfirm>
          </>}
          {(record.status !== 1) && <>
            <Popconfirm title="是否要删除此数据？" cancelText='取消' okText='确认' onConfirm={() => delCredential(record.id)}>
              <a>删除</a>
            </Popconfirm>
          </>}
          {(record.hangStatus === 1 ||  record.hangStatus === 3) && <>
            {(record.hangBpmUrl) && <><a onClick={() => window.open(record.hangBpmUrl)}> 审批详情 </a></>}
          </>}
          {(record.hangStatus === 2) && <>
            <a onClick={() => dismissOrDetails(record,'解除')}>申请解除</a>
            <Divider type="vertical"/>
            <a onClick={() => dismissOrDetails(record,'详情')}>详情</a>
          </>}
        </>
      ),
    }
  ];

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        request={(params) => getCredentialList(params)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => addCredential(null)}><PlusOutlined/>新增</Button>
        ]}
      />
      <AddForm
        loading={loading}
        visible={visible}
        orgTree={orgTree}
        config={config}
        record={record}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <Details
        config={config}
        onCancel={handleCancel}
        onSubmit={(record) => saveOrDelHang(record.id,4)}
        record={record}
        orgTree={orgTree}
        title={title}
        detailsVisible={detailsVisible}
      />
    </PageHeaderWrapper>
  )
};

export default connect(({global,user}) => ({global,currentUser:user.currentUser}))(TableList)
